package com.lqm.web.controller.home;

import com.lqm.entity.home.HomeUser;
import com.lqm.entity.home.Project;
import com.lqm.entity.home.ProjectScore;
import com.lqm.service.home.ProjectScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: CrowdFunding
 * @description
 * @author: lqm
 * @create: 2018-12-16 17:11
 */
@RestController
@RequestMapping("home")
public class ProjectScoreController {

    @Autowired
    ProjectScoreService projectScoreService;

    @RequestMapping("getProjectScoreAvgByProjectId")
    public Map<String, Object> getProjectScoreAvgByProjectId(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        Project project = new Project();
        project.setProjectId(id);
        Double avg = projectScoreService.findAvgByProjectId(project);
        map.put("data",avg);
        return map;
    }

    @RequestMapping("addProjectScore")
    public Map<String, Object> addProjectScore(ProjectScore projectScore, HttpSession session) {

        HashMap<String, Object> map = new HashMap<>();
        HomeUser user = (HomeUser) session.getAttribute("home_user");
        projectScore.setHomeUser(user);
        System.out.println(projectScore);
        int i = projectScoreService.saveScore(projectScore);
        if (i==0){//重复提交了
            map.put("code",101);
            map.put("msg","您已经评分过了");
        }else {
            map.put("code",0);
            map.put("msg","评价成功");
        }

        return map;
    }

    @RequestMapping("findAllScoreByProject")
    public Map<String, Object> findAllScoreByProject(Project project,int limit,int page) {
        HashMap<String, Object> map = new HashMap<>();

        List<ProjectScore> allScoreByProject = projectScoreService.findAllScoreByProject(project, limit, page);
        for (ProjectScore projectScore : allScoreByProject) {
            HomeUser homeUser = projectScore.getHomeUser();
            homeUser.setProjects(null);
            projectScore.setHomeUser(homeUser);
        }

        map.put("data",allScoreByProject);
        return map;
    }
}
